﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    /// <summary>
    /// UBE 报表执行
    /// </summary>
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class UBEController : ControllerBase
    {
        /// <summary>
        /// 指定名称和版本的报表执行
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> RST4252AExecute(dynamic objpram)
        {
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string reportName = "RST4252A";
            string reportVersion = objpram["reportVersion"].ToString();
            string company = objpram["company"].ToString();
            string ordertype = objpram["ordertype"].ToString();
            string ordernumber = objpram["ordernumber"].ToString();
            string region = "";
            try
            {
                region = objpram["region"].ToString();
            }
            catch { }
            string orderlist = "";
            try
            {
                orderlist = objpram["orderlist"].ToString();
            }
            catch { }



            try
            {
                //2021-08-25 因出现大批量莫名杀单，整箱拍单功能暂停排查原因
                //if (reportVersion.Equals("MBR008"))
                //{
                //    throw new MQException("505", $"整箱拍单暂时停用，请联系物流在E1中处理！");
                //}



                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new MQException("401","请求的用户名或密码为空！");
                }
                //try
                //{
                //    OAuthController oAuth = new OAuthController();
                //    oAuth.GetToken(objpram);
                //}
                //catch (MQException x)
                //{
                //    throw x;
                //}
                //if (string.IsNullOrWhiteSpace(SomeHandler.GetToken(username)))
                //{
                //    throw new MQException("401","验证失败，请检查用户名密码是否正确！");
                //}
                //string token = SomeHandler.GetToken(username);
                string token = SomeHandler.GetToken(username, password);
                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }
               
                Console.WriteLine($"{DateTime.Now.ToString()} 执行报表{reportName}");


                List<criteria> criterias = new List<criteria>();

                criterias.Add(new criteria()
                {
                    comparisonType = "EQUAL",
                    predicate = new SelectionValue()
                    {
                        literalType = "SINGLE",
                        values = new string[] { ordertype }

                    },
                    subject = new SelectionValue()
                    {
                        view = "V4211",
                        dictItem = "DCTO",
                        table = "F4211"
                    }
                });
                if (!string.IsNullOrWhiteSpace(company))
                {
                    criterias.Add(new criteria()
                    {
                        comparisonType = "EQUAL",
                        @operator = "AND",
                        predicate = new SelectionValue()
                        {
                            literalType = "SINGLE",
                            values = new string[] { company }

                        },
                        subject = new SelectionValue()
                        {
                            view = "V4211",
                            dictItem = "KCOO",
                            table = "F4211"
                        }
                    });
                }

                if (!string.IsNullOrWhiteSpace(region))
                {
                    if (region.Equals("NC"))
                    {
                        criterias.Add(new criteria()
                        {
                            comparisonType = "EQUAL",
                            @operator = "AND",
                            predicate = new SelectionValue()
                            {
                                literalType = "SINGLE",
                                values = new string[] { "93000" }

                            },
                            subject = new SelectionValue()
                            {
                                view = "V4211",
                                dictItem = "KCOO",
                                table = "F4211"
                            }
                        });
                    }
                    else if (region.Equals("EC"))
                    {
                        criterias.Add(new criteria()
                        {
                            comparisonType = "EQUAL",
                            @operator = "AND",
                            predicate = new SelectionValue()
                            {
                                literalType = "SINGLE",
                                values = new string[] { "91000" }

                            },
                            subject = new SelectionValue()
                            {
                                view = "V4211",
                                dictItem = "KCOO",
                                table = "F4211"
                            }
                        });
                    }
                    else if (region.Equals("SC"))
                    {
                        criterias.Add(new criteria()
                        {
                            comparisonType = "VALUE_IN_LIST",
                            @operator = "AND",
                            predicate = new SelectionValue()
                            {
                                literalType = "LIST",
                                values = new string[] { "  ZGZ0200241", "  ZGZ0200240", "  ZGZ0200243" }

                            },
                            subject = new SelectionValue()
                            {
                                view = "V4211",
                                dictItem = "MCU",
                                table = "F4211"
                            }
                        });
                    }
                    else if (region.Equals("WC"))
                    {
                        criterias.Add(new criteria()
                        {
                            comparisonType = "VALUE_IN_LIST",
                            @operator = "AND",
                            predicate = new SelectionValue()
                            {
                                literalType = "LIST",
                                values = new string[] { "  ZGZ0200244", "  ZGZ0200242", "  ZGZ0200245" }

                            },
                            subject = new SelectionValue()
                            {
                                view = "V4211",
                                dictItem = "MCU",
                                table = "F4211"
                            }
                        });
                    }
                    else //兼容旧代码
                    {
                        criterias.Add(new criteria()
                        {
                            comparisonType = "EQUAL",
                            @operator = "AND",
                            predicate = new SelectionValue()
                            {
                                literalType = "SINGLE",
                                values = new string[] { "92" }

                            },
                            subject = new SelectionValue()
                            {
                                view = "V4211",
                                dictItem = "KCOO",
                                table = "F4211"
                            }
                        });
                    }
                }

                //2021-07-05 增加指定单号的处理
                if (!string.IsNullOrWhiteSpace(ordernumber))
                {
                    criterias.Add(new criteria()
                    {
                        comparisonType = "EQUAL",
                        @operator = "AND",
                        predicate = new SelectionValue()
                        {
                            literalType = "SINGLE",
                            values = new string[] { ordernumber }

                        },
                        subject = new SelectionValue()
                        {
                            view = "V4211",
                            dictItem = "DOCO",
                            table = "F4211"
                        }
                    });
                }


                if (!string.IsNullOrWhiteSpace(orderlist))
                {
                    criterias.Add(new criteria()
                    {
                        comparisonType = "VALUE_IN_LIST",
                        @operator = "AND",
                        predicate = new SelectionValue()
                        {
                            literalType = "LIST",
                            values = orderlist.Split(',')

                        },
                        subject = new SelectionValue()
                        {
                            view = "V4211",
                            dictItem = "DOCO",
                            table = "F4211"
                        }
                    });
                }


                LaunchUBERequest request = new LaunchUBERequest()
                {
                    reportName = reportName,
                    reportVersion = reportVersion,
                    fireAndForget=false,
                    dataSelection = new DataSelection()
                    { criteria = criterias.ToArray() }
                };

                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                };

                Console.WriteLine( JsonConvert.SerializeObject(request, settings));


                ReportserviceResponse response = AISClientHandler.Instance.ReportService_execute(token, request);
                JObject obj = response.ToJObject();
                execresult.Result = obj["jobNumber"].ToString();
                execresult.Message = response.ToString();

                Log4Net.Info(response.JsonString);
                Console.WriteLine($"{DateTime.Now.ToString()}  jobno:{execresult.Result}");
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }
    }
}